<script lang="ts" setup>
import { SearchTable } from '@fl/components'
import type { VxeTableInstance } from 'vxe-table'
import type { PlusFormGroupRow } from 'plus-pro-components'
import FlUploadProgress from '@fl/components/fl-upload-progress.vue'
import ImportGoods from './import-goods.vue'
import SelectAgreement from './select-agreement.vue'
import { useContractForm } from './useContractForm'
import { OPERATE_STATE } from './constant'
import { cloneDeep } from 'lodash-es'
import { useDeletedFile, useGetContractSupplierLabel, useSignFile } from '@fl/api/mall-api'
import { useGetAuthUrl } from '@fl/api/supplier'

const props = defineProps({
    // 初始表单数据
    initialData: {
        type: Object,
        default: () => ({}),
    },
    isSupplier: {
        type: Boolean,
        default: false,
    },

})

const emit = defineEmits(['submit', 'save', 'reject', 'back', 'auditPass', 'sign'])

const { push } = useRouter()
const { meta: { isAdmin } } = useRoute()
const { mutate: signFileMutate, isPending: signFileLoading } = useSignFile()

const authUrlParams = computed(() => ({
    redirectUrl: location.href,
    flag: !isAdmin,
}))

const { data: authUrlData } = useGetAuthUrl(authUrlParams)

const { mutate: deleteFileMutate } = useDeletedFile()

const key = ref(1)

const isFirst = ref<boolean>(true)

const { data: supplierLabel } = useGetContractSupplierLabel(!isAdmin)

const partBOptions = computed(() => {
    return supplierLabel.value || []
})

const tableRef = ref<VxeTableInstance>()

const showImportGoods = ref(false)

const showSelectAgreement = ref(false)

const agreementId = ref<string | undefined>(undefined)

const categoryId = ref<string | undefined>(undefined)

const canEditTable = computed(() => {
    return ['待乙方签约'].includes(OPERATE_STATE[state.value.status]) && state.value.flag === 1
})

const gridOptions = computed<any>(() => ({
    columns: [
        { field: 'productName', title: '产品名称', minWidth: 200 },
        { field: 'skuName', title: '商品名称', minWidth: 100 },
        { field: 'brand', title: '品牌', minWidth: 100 },
        { field: 'model', title: '型号', minWidth: 100 },
        { field: 'category', title: '产品类目', minWidth: 100 },
        { field: 'unit', title: '单位', minWidth: 100 },

        {
            editRender: !canEditTable.value ? undefined : { attrs: { type: 'number' }, name: 'input', placeholder: '请输入价格(不含税)' },
            field: 'sellingPrice',
            slots: { default: 'selling_price' },
            title: '价格(元,不含税)',
            minWidth: 180,
        },
        {
            editRender: !canEditTable.value ? undefined : { attrs: { type: 'number' }, name: 'input', placeholder: '请输入价格(含税)' },
            field: 'agreementPrice',
            slots: { default: 'agreement_price' },
            title: '价格(元,含税)',
            minWidth: 180,
        },
        {
            editRender: !canEditTable.value ? undefined : { attrs: { type: 'number' }, name: 'input', placeholder: '请输入采购数量' },
            field: 'count',
            slots: { default: 'count' },
            title: '采购数量',
            minWidth: 160,
        },
        { fixed: 'right', slots: { default: 'operation' }, title: '操作', width: 100, visible: canEditTable.value },
    ],
    editConfig: {
        mode: 'cell',
        trigger: 'click',
    },
    editRules: !canEditTable.value
        ? {}
        : {
                agreementPrice: [
                    { message: '必须填写价格(含税)', required: true, trigger: 'change', validator: (cell) => {
                        if (!cell.cellValue) {
                            return new Error('必须填写价格(含税)')
                        }
                        if (Number(cell.cellValue) <= 0 || Number(cell.cellValue) > 99999999999999) {
                            return new Error('价格应大于0,小于99999999999999')
                        }
                    } },
                ],
                count: [
                    { message: '必须填写采购数量', required: true, trigger: 'change', validator: (cell) => {
                        if (!cell.cellValue) {
                            return new Error('必须填写采购数量')
                        }
                        if (Number(cell.cellValue) <= 0 || Number(cell.cellValue) > 99999999999999) {
                            return new Error('价格应大于0,小于99999999999999')
                        }
                    } },
                ],
                sellingPrice: [
                    { message: '必须填写价格(不含税)', required: true, trigger: 'change', validator: (cell) => {
                        if (!cell.cellValue) {
                            return new Error('必须填写价格(不含税)')
                        }
                        if (Number(cell.cellValue) <= 0 || Number(cell.cellValue) > 99999999999999) {
                            return new Error('价格应大于0,小于99999999999999')
                        }
                    } },
                ],
            },
    validConfig: {
        autoPos: false,
        msgMode: 'full',
    },
    maxHeight: 600,
    minHeight: 0,
}))

const isReadMode = computed(() => isAdmin || state.value.flag !== 1
    || !['草稿', '待甲方发起'].includes(OPERATE_STATE[state.value.status]))

const { formRef, state, rules, fileType, back } = useContractForm()

const hasFooter = computed(() => {
    if (isAdmin) {
        return false
    }
    if (props.isSupplier) {
        return state.value.flag === 1 && ['待乙方签约'].includes(OPERATE_STATE[state.value.status])
    }
    return state.value.flag === 1 && ['草稿', '待甲方发起', '待甲方签约'].includes(OPERATE_STATE[state.value.status])
})

const showCancelBtn = computed(() => {
    if (isAdmin || props.isSupplier) {
        return false
    }
    return ['草稿', '待甲方发起'].includes(OPERATE_STATE[state.value.status]) && state.value.flag === 1
})

const showSaveBtn = computed(() => {
    if (isAdmin || props.isSupplier) {
        return false
    }
    return ['草稿', '待甲方发起'].includes(OPERATE_STATE[state.value.status]) && isFirst.value && state.value.flag === 1
})

const showSubmitBtn = computed(() => {
    if (isAdmin || props.isSupplier) {
        return false
    }
    return ['草稿', '待甲方发起'].includes(OPERATE_STATE[state.value.status]) && !isFirst.value && state.value.flag === 1
})

const showSignBtn = computed(() => {
    if (!props.isSupplier) {
        return ['草稿', '待甲方发起'].includes(OPERATE_STATE[state.value.status]) && isFirst.value && state.value.flag === 1
    }
    return false
})

const showAuditBtn = computed(() => {
    if (props.isSupplier) {
        return ['待乙方签约'].includes(OPERATE_STATE[state.value.status]) && state.value.flag === 1
    }
    return ['待甲方签约'].includes(OPERATE_STATE[state.value.status]) && state.value.flag === 1
})

// 驳回相关
const rejectedVisible = ref<boolean>(false)
const dialogForm = ref()
const rejectedState = ref({
    remark: '',
    files: [],
})

const rejectedCloumns: any = [
    {
        fieldProps: {
            'maxlength': 200,
            'show-word-limit': true,
            'autosize': {
                minRows: 4,
            },
            'resize': 'none',
        },
        label: '驳回原因',
        labelWidth: 100,
        prop: 'remark',
        valueType: 'textarea',
    },
    {
        label: '附件',
        labelWidth: 100,
        prop: 'files',
    },
]

const rejectedStateRules = {
    remark: [
        {
            required: true,
            message: '请输入驳回原因',
        },
    ],
}

const finalGroup = computed<PlusFormGroupRow[]>(() => {
    return [
        {
            title: '协议',
            columns: [
                {
                    fieldProps: computed(() => {
                        return {
                            onChange: () => {
                                delAgreement()
                            },
                        }
                    }),
                    label: '是否关联协议',
                    prop: 'isAssociated',
                    valueType: isReadMode.value ? 'text' : 'radio',
                    options: !isReadMode.value
                        ? [
                                { label: '是', value: '是' },
                                { label: '否', value: '否' },
                            ]
                        : undefined,
                },
                {
                    label: '选择协议',
                    prop: 'relationAgreementId',
                    hideInForm: computed(() =>
                        state.value.isAssociated === '否',
                    ),
                },
            ],
        },
        {
            title: '签署方信息',
            columns: [
                {
                    colProps: { span: 8 },
                    label: '甲方',
                    prop: 'partyA',
                    valueType: 'text',
                },
                {

                    fieldProps: computed(() => ({ disabled: Boolean(state.value.relationAgreementId) || state.value.source === 2, filterable: true })),
                    colProps: { span: 8 },
                    label: '乙方',
                    prop: isReadMode.value ? 'partyB' : 'partyBId',
                    valueType: isReadMode.value ? 'text' : 'select',
                    options: !isReadMode.value
                        ? partBOptions.value
                        : undefined,

                },
            ],
        },
        {
            title: '合同信息',
            columns: [
                {
                    colProps: {
                        span: 8,
                    },
                    fieldProps: isReadMode.value
                        ? undefined
                        : {
                                maxlength: 100,
                            },
                    label: '合同名称',
                    prop: 'agreementName',
                    valueType: isReadMode.value ? 'text' : 'input',
                },
                {
                    colProps: {
                        span: 8,
                    },
                    label: '合同有效期',
                    prop: isReadMode.value ? 'initiationTimeText' : 'initiationTime',
                    valueType: isReadMode.value ? 'text' : 'date-picker',
                    fieldProps: !isReadMode.value
                        ? {
                                type: 'daterange',
                                format: 'YYYY-MM-DD',
                                valueFormat: 'YYYY-MM-DD',
                                disabledDate: (time: any) => {
                                    return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
                                },
                            }
                        : undefined,
                },
                {
                    colProps: {
                        span: 24,
                    },
                    label: '合同金额',
                    prop: 'priceType',
                },
            ],
        },
        {
            title: '合同文件',
            columns: [
                {
                    label: '合同上传',
                    prop: 'contractFileList',
                },
                {
                    label: '附件上传',
                    prop: 'otherFileList',
                },
            ],
        },
        {
            title: '商品清单',
            columns: [
                {
                    colProps: {
                        span: 24,
                    },
                    label: '商品清单',
                    prop: 'productList',
                    hasLabel: false,
                },
            ],
            hideInGroup: computed(() => {
                if (props.isSupplier) {
                    return ['草稿', '待甲方发起'].includes(OPERATE_STATE[state.value.status])
                }
                return ['草稿', '待甲方发起', '待乙方签约'].includes(OPERATE_STATE[state.value.status])
            }),
        },
        {
            title: '签约状态',
            columns: [
                {
                    label: '乙方',
                    prop: 'partyB',
                    valueType: 'text',

                },
                {
                    label: '审核结果',
                    prop: 'auditBResult',
                    valueType: 'text',

                },
                {
                    label: '签章时间',
                    prop: 'partyBSignTime',
                    valueType: 'text',
                    hideInForm: computed(() => {
                        return !(state.value.auditBResult === '通过')
                    },
                    ),

                },
                {
                    label: '驳回理由',
                    prop: 'rejectReason',
                    valueType: 'text',
                    hideInForm: computed(() => {
                        return state.value.auditBResult === '通过'
                    },
                    ),
                },
                {
                    label: '附件',
                    prop: 'rejectFileList',
                    valueType: 'text',
                    hideInForm: computed(() => {
                        return state.value.auditBResult === '通过'
                    },
                    ),
                },
                {
                    label: 'divider',
                    prop: 'divider',
                    valueType: 'divider',
                    hasLabel: false,
                    hideInForm: computed(() => {
                        return ['待甲方签约', '乙方已驳回'].includes(OPERATE_STATE[state.value.status])
                    }),
                },
                {
                    label: '甲方',
                    prop: 'partyA',
                    valueType: 'text',
                    hideInForm: computed(() => {
                        return ['待甲方签约', '乙方已驳回'].includes(OPERATE_STATE[state.value.status])
                    }),
                },
                {
                    label: '审核结果',
                    prop: 'auditAResult',
                    valueType: 'text',
                    hideInForm: computed(() => {
                        return ['待甲方签约', '乙方已驳回'].includes(OPERATE_STATE[state.value.status])
                    }),
                },
                {
                    label: '签章时间',
                    prop: 'partyASignTime',
                    valueType: 'text',
                    hideInForm: computed(() => {
                        if (['待甲方签约', '乙方已驳回'].includes(OPERATE_STATE[state.value.status]) || !(state.value.auditAResult === '通过')) {
                            return true
                        }
                        return false
                    }),
                },
                {
                    label: '驳回理由',
                    prop: 'rejectReason',
                    valueType: 'text',
                    hideInForm: computed(() => {
                        if (['待甲方签约', '乙方已驳回'].includes(OPERATE_STATE[state.value.status]) || state.value.auditAResult === '通过') {
                            return true
                        }
                        return false
                    }),
                },
                {
                    label: '附件',
                    prop: 'rejectFileList',
                    valueType: 'text',
                    hideInForm: computed(() => {
                        if (['待甲方签约', '乙方已驳回'].includes(OPERATE_STATE[state.value.status]) || state.value.auditAResult === '通过') {
                            return true
                        }
                        return false
                    }),
                },
            ],
            hideInGroup: ['草稿', '待甲方发起', '待乙方签约'].includes(OPERATE_STATE[state.value.status]),
        },
    ]
})

// 方法
function handleBack() {
    if (['草稿', '待甲方发起'].includes(OPERATE_STATE[state.value.status])) {
        if (!isFirst.value) {
            isFirst.value = true
            return
        }
    }
    back()
}

async function handleSign() {
    const res = await formRef.value.formInstance.validate()
    if (res) {
        emit('sign', getSubmitForm())
    }
}

function getSubmitForm() {
    const result = {
        ...state.value,
        startDate: state.value?.initiationTime?.[0] || '',
        endDate: state.value?.initiationTime?.[1] || '',
        partyB: state.value.partyBId ? partBOptions.value.find((item: any) => item.value === state.value.partyBId)?.label : '',
        agreementType: 2,
        contractFileList: state.value.contractFileList?.map((item: any) => {
            return item.id
                ? {
                        id: item.id ?? '',
                        fileName: item.name,
                        fileUrl: item.url,
                    }
                : {
                        fileName: item.name,
                        fileUrl: item.url,
                    }
        }) || [],
        otherFileList: state.value.otherFileList?.map((item: any) => {
            return item.id
                ? {
                        id: item.id ?? '',
                        fileName: item.name,
                        fileUrl: item.url,
                    }
                : {
                        fileName: item.name,
                        fileUrl: item.url,
                    }
        }) || [],
    }
    return result
}

async function save() {
    const res = await formRef.value.formInstance.validate()
    if (res) {
        emit('save', getSubmitForm())
    }
}

function formSubmit() {
    emit('submit', getSubmitForm())
}

function rejected() {
    rejectedVisible.value = true
}

async function auditPass() {
    const $table = (tableRef.value as any)?.tableInstance
    if ($table) {
        const errMap = await $table.fullValidate(true)
        if (errMap) {
            return
        }
    }
    emit('auditPass', getSubmitForm())
}

async function handleAllConfirm(handleSubmit) {
    const isPass = await handleSubmit()
    if (isPass) {
        emit('reject', {
            ...rejectedState.value,
            files: rejectedState.value.files.map((item: any) => {
                return {
                    fileName: item.name,
                    fileUrl: item.url,
                }
            }),
            ...getSubmitForm(),
        })
        rejectedVisible.value = false
    }
}

function handleReset() {
    rejectedVisible.value = false
}

function reset() {
    dialogForm.value.formInstance.resetFields()
}
function handleRadioChange() {
    state.value.contractPrice = 0
    state.value.a12 = ''
}

function onImportGoodsBtnClick() {
    showImportGoods.value = true
}

function onRemoveBtnClick(row: any) {
    const $table = (tableRef.value as any)?.tableInstance
    if ($table) {
        $table.remove(row)
    }
}

function confirm(val: any[]) {
    state.value.productList = val.map((item: any) => ({
        agreementPrice: '',
        attribute: item.attribute,
        brand: item.brandName,
        category: item.categoryPath,
        model: item.productModel,
        oldPrice: item.oldPrice,
        productCode: item.productNo,
        productId: item.productId,
        productName: item.productName,
        skuId: item.skuId,
        skuName: item.skuName,
        skuUrl: item.productImage,
        unit: item.productUnit,
    }))
}

function confirmAgreement(val: any) {
    state.value.relationAgreementId = val.id
    state.value.relationAgreementName = val.agreementName
    if (state.value.source !== 2) {
        state.value.partyBId = val.partyBId
    }
}

function delAgreement() {
    state.value.relationAgreementId = ''
    state.value.relationAgreementName = ''
    if (state.value.source !== 2) {
        state.value.partyBId = ''
    }
}

function changeIsFirst() {
    isFirst.value = false
}

function showSign(file: any) {
    if (isAdmin || state.value.flag !== 1) {
        return false
    }
    if (props.isSupplier) {
        return file.unEsign === 2 && ['待乙方签约'].includes(OPERATE_STATE[state.value.status])
    }
    if (['草稿', '待甲方发起'].includes(OPERATE_STATE[state.value.status])) {
        return file.unEsign === 2 && !isFirst.value
    }
    if (['待甲方签约'].includes(OPERATE_STATE[state.value.status])) {
        return file.unEsign === 2
    }
    return false
}

function showViewSign(file: any) {
    if (isAdmin || state.value.flag !== 1) {
        return false
    }

    if (file.unEsign === 1) {
        return true
    }

    return false
}
function showTag(file: any) {
    if (isAdmin) {
        return false
    }
    return file.unEsign === 1
}
function goSign(file: any) {
    if (!state.value.id) {
        return
    }
    signFileMutate({
        agreementId: state.value.id,
        fileId: file.id,
    }, {
        onSuccess: (res) => {
            if (Number(res) === 1) {
                ElMessageBox.confirm('未授权电子签章', '提示', {
                    confirmButtonText: '去授权',
                    cancelButtonText: '取消',
                    type: 'warning',

                }).then(() => {
                    if (!unref(authUrlData)?.authUrl) {
                        return
                    }
                    window.open(unref(authUrlData)?.authUrl, '_self')
                })
                return
            }
            window.open(res)
        },
    })
}

function removeFile(file: any) {
    if (file.id) {
        deleteFileMutate(file.id)
    }
}

function showAgreement() {
    if (isAdmin) {
        push(`/operations-pages/operations-order-management/sign-agreen?id=${state.value.relationAgreementId}`)
        return
    }
    if (props.isSupplier) {
        push(`/supplier-pages/order-management/sign-agreen?id=${state.value.relationAgreementId}`)
        return
    }
    push(`/purchase-pages/purchase-order-management/sign-agreen?id=${state.value.relationAgreementId}`)
}

watchEffect(() => {
    if (props.initialData) {
        state.value = cloneDeep({
            ...props.initialData,
            isAssociated: props.initialData?.relationAgreementId ? '是' : '否',
            contractPrice: props.initialData?.contractPrice ? Number(props.initialData?.contractPrice) : 0,
            initiationTime: props.initialData?.startDate && props.initialData?.endDate ? [props.initialData?.startDate, props.initialData?.endDate] : [],
            initiationTimeText: props.initialData?.startDate && props.initialData?.endDate ? `${props.initialData?.startDate} 至 ${props.initialData?.endDate}` : '-',
            contractFileList: props.initialData?.contractFileList?.map((item: any) => {
                return {
                    ...item,
                    name: item.fileName,
                    url: item.fileUrl,
                }
            }) || [],
            otherFileList: props.initialData?.otherFileList?.map((item: any) => {
                return {
                    ...item,
                    name: item.fileName,
                    url: item.fileUrl,
                }
            }) || [],
            rejectFileList: props.initialData?.rejectFileList?.map((item: any) => {
                return {
                    ...item,
                    name: item.fileName,
                    url: item.fileUrl,
                }
            }) || [],
            auditAResult: ['甲方已驳回'].includes(OPERATE_STATE[props.initialData.status]) ? '驳回' : '通过',
            auditBResult: ['乙方已驳回'].includes(OPERATE_STATE[props.initialData.status]) ? '驳回' : '通过',
            priceType: props.initialData?.priceType || 1,
        })

        key.value++
    }
})

watch(() => state.value.contractFileList, () => {
    if (['草稿', '待甲方发起'].includes(OPERATE_STATE[state.value.status])) {
        formRef.value?.formInstance?.validateField('contractFileList')
    }
}, {
    deep: true,
})

watch(() => state.value.relationAgreementId, () => {
    if (['草稿', '待甲方发起'].includes(OPERATE_STATE[state.value.status])) {
        formRef.value?.formInstance?.validateField('relationAgreementId')
    }
}, {
    deep: true,
})

defineExpose({ changeIsFirst })
</script>

<template>
    <div class="flex justify-between">
        <ElButton type="primary"
                  class="mb-20"
                  @click="handleBack"
        >
            返回
        </ElButton>

        <el-tag type="primary">
            {{ OPERATE_STATE[state.status] }}
        </el-tag>
    </div>

    <PlusForm ref="formRef"
              :key="key"
              v-model="state"
              :group="finalGroup"
              :rules="isReadMode ? {} : rules"
              :row-props="{ gutter: 20 }"
              :label-width="0"
              :has-footer="hasFooter"
              @submit="formSubmit"
    >
        <template #plus-field-relationAgreementId>
            <div class="flex flex-col gap-5">
                <ElButton v-if="!isReadMode"
                          style="width: fit-content"
                          @click="showSelectAgreement = true"
                >
                    选择协议
                </ElButton>

                <div v-if="state.relationAgreementId">
                    协议名称:  {{ state.relationAgreementName }}
                    <ElButton type="primary"
                              text
                              @click="showAgreement"
                    >
                        查看
                    </ElButton>

                    <ElButton v-if="!isReadMode"
                              type="danger"
                              text
                              @click="delAgreement"
                    >
                        删除
                    </ElButton>
                </div>
            </div>
        </template>

        <template #plus-field-priceType>
            <el-radio-group v-if="!isReadMode"
                            v-model="state.priceType"
                            class="money-radio"
                            @change="handleRadioChange"
            >
                <el-radio :value="1">
                    金额:
                    <el-input-number v-model="state.contractPrice"
                                     :precision="2"
                                     :max="999999999999999"
                                     :min="0"
                                     style="width: 350px;margin-left: 20px;"
                                     :disabled="state.priceType !== 1 "
                    />

                    <div class="px-10 bg-#f5f7fa">
                        元
                    </div>
                </el-radio>

                <!-- <el-radio value="2">
                    其他:
                    <el-input v-model="state.a12"
                              :disabled="state.priceType !== '2' "
                              style="width: 350px;margin-left: 20px;"
                              :rows="2"
                              :maxlength="12"
                              type="textarea"
                              placeholder="请输入"
                              resize="none"
                    />
                </el-radio> -->
            </el-radio-group>

            <template v-else>
                <span v-if="state.priceType === 1"
                      class="el-text"
                >
                    {{ state.contractPrice }} 元
                </span>

                <!-- <span v-else>
                    其他: {{ state.a12 }}
                </span> -->
            </template>
        </template>

        <template #plus-field-contractFileList>
            <FlUploadProgress v-model="state.contractFileList"
                              list-type="text"
                              :limit="10"
                              :file-size="50"
                              :accept="fileType"
                              tips
                              :disabled="isReadMode || !isFirst"
                              @remove="removeFile"
            >
                <template #operate="{ file }">
                    <ElTag v-if="showTag(file)"
                           type="primary"
                    >
                        {{ props.isSupplier ? '乙方' : '甲方' }}已签章
                    </ElTag>

                    <ElButton v-if="showSign(file)"
                              type="primary"
                              style="margin-left: 10px"
                              :disabled="signFileLoading"
                              size="small"
                              @click="goSign(file)"
                    >
                        在线签章
                    </ElButton>

                    <ElButton v-if="showViewSign(file)"
                              type="primary"
                              style="margin-left: 10px"
                              :disabled="signFileLoading"
                              size="small"
                              @click="goSign(file)"
                    >
                        预览签章文件
                    </ElButton>
                </template>
            </FlUploadProgress>
        </template>

        <template #plus-field-otherFileList>
            <FlUploadProgress v-model="state.otherFileList"
                              list-type="text"
                              :limit="10"
                              :file-size="50"
                              :accept="fileType"
                              tips
                              :disabled="isReadMode || !isFirst"
                              @remove="removeFile"
            >
                <template #operate="{ file }">
                    <ElTag v-if="showTag(file)"
                           type="primary"
                    >
                        {{ props.isSupplier ? '乙方' : '甲方' }}已签章
                    </ElTag>

                    <ElButton v-if="showSign(file)"
                              type="primary"
                              style="margin-left: 10px"
                              :disabled="signFileLoading"
                              size="small"
                              @click="goSign(file)"
                    >
                        在线签章
                    </ElButton>

                    <ElButton v-if="showViewSign(file)"
                              type="primary"
                              style="margin-left: 10px"
                              :disabled="signFileLoading"
                              size="small"
                              @click="goSign(file)"
                    >
                        预览签章文件
                    </ElButton>
                </template>
            </FlUploadProgress>
        </template>

        <template #plus-field-rejectFileList>
            <FlUploadProgress v-model="state.rejectFileList"
                              list-type="text"
                              :limit="10"
                              :file-size="50"
                              :accept="fileType"
                              tips
                              :disabled="isReadMode"
            />
        </template>

        <template #plus-field-productList>
            <SearchTable v-bind="gridOptions"
                         ref="tableRef"
                         :data="state.productList"
                         class="w-full"
            >
                <template #operation="{ row }">
                    <ElButton text
                              type="danger"
                              class="!p-4"
                              @click="onRemoveBtnClick(row)"
                    >
                        删除
                    </ElButton>
                </template>

                <template #selling_price="{ row }">
                    <el-input v-if="canEditTable"
                              v-model="row.sellingPrice"
                              placeholder="请输入价格(不含税)"
                              type="number"
                    />

                    <span v-else>{{ row.sellingPrice }}</span>
                </template>

                <template #agreement_price="{ row }">
                    <el-input v-if="canEditTable"
                              v-model="row.agreementPrice"
                              placeholder="请输入价格(含税)"
                              type="number"
                    />

                    <span v-else>{{ row.agreementPrice }}</span>
                </template>

                <template #count="{ row }">
                    <el-input v-if="canEditTable"
                              v-model="row.count"
                              placeholder="请输入采购数量"
                              type="number"
                    />

                    <span v-else>{{ row.count }}</span>
                </template>

                <template v-if="canEditTable"
                          #toolbar_buttons
                >
                    <el-space>
                        <ElButton type="primary"
                                  @click="onImportGoodsBtnClick"
                        >
                            <div class="i-ic:baseline-add size-16" />
                            引入商品
                        </ElButton>
                    </el-space>
                </template>
            </SearchTable>
        </template>

        <template #plus-field-auditBResult>
            <span :style="{ color: state.auditBResult === '通过' ? '#3d9dea' : '#ec3535' }">{{ state.auditBResult }}</span>
        </template>

        <template #plus-field-auditAResult>
            <span :style="{ color: state.auditAResult === '通过' ? '#3d9dea' : '#ec3535' }">{{ state.auditAResult }}</span>
        </template>

        <template #footer="{ handleSubmit }">
            <div style="margin: 0 auto">
                <ElButton v-if="showCancelBtn"
                          @click="handleBack"
                >
                    取消
                </ElButton>

                <ElButton v-if="showSaveBtn"
                          @click="save"
                >
                    保存
                </ElButton>

                <ElButton v-if="showSubmitBtn"
                          type="primary"
                          @click="handleSubmit"
                >
                    提交
                </ElButton>

                <ElButton v-if="showSignBtn"
                          type="primary"
                          @click="handleSign"
                >
                    去签章
                </ElButton>

                <template v-if="showAuditBtn">
                    <ElButton @click="rejected">
                        驳回
                    </ElButton>

                    <ElButton type="primary"
                              @click="auditPass"
                    >
                        确认签约
                    </ElButton>
                </template>
            </div>
        </template>
    </PlusForm>

    <!-- 驳回对话框 -->
    <PlusDialogForm ref="dialogForm"
                    v-model:visible="rejectedVisible"
                    v-model="rejectedState"
                    :form="{ columns: rejectedCloumns, hasFooter: true, rules: rejectedStateRules }"
                    title="驳回"
                    :dialog="{ hasFooter: false }"
                    @closed="reset"
    >
        <template #plus-field-files>
            <FlUploadProgress v-model="rejectedState.files"
                              list-type="text"
                              :limit="10"
                              :file-size="50"
                              :accept="fileType"
                              tips
            />
        </template>

        <template #form-footer="{ handleSubmit }">
            <div style="margin: 0 auto">
                <ElButton type="primary"
                          @click="handleAllConfirm(handleSubmit)"
                >
                    提交
                </ElButton>

                <ElButton @click="handleReset">
                    返回
                </ElButton>
            </div>
        </template>
    </PlusDialogForm>

    <ImportGoods v-if="!isAdmin"
                 :key="String(showImportGoods)"
                 v-model:visible="showImportGoods"
                 :agreement-id="agreementId"
                 :category-id="categoryId"
                 @confirm="confirm"
    />

    <SelectAgreement v-if="!isAdmin"
                     :id="state.relationAgreementId"
                     :key="String(showSelectAgreement)"
                     v-model:visible="showSelectAgreement"
                     :is-supplier="isSupplier"
                     :is-admin="isAdmin"
                     @confirm="confirmAgreement"
    />
</template>

<style lang="scss" scoped>
.money-radio {
    gap: 30px;
    flex-direction: column;
    align-items: flex-start;

    :deep(.el-radio__label) {
        display: flex;
        align-items: center;
    }
}
</style>
